package com.woniu.zsd.permission.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.commons.util.DateUtils;
import com.woniu.dto.AdminInfoDto;
import com.woniu.form.*;
import com.woniu.zsd.commons.exception.ZsdException;
import com.woniu.zsd.permission.entity.AdminInfo;
import com.woniu.zsd.permission.mapper.AdminInfoMapper;
import com.woniu.zsd.permission.service.IAdminInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class AdminInfoServiceImpl extends ServiceImpl<AdminInfoMapper, AdminInfo> implements IAdminInfoService {
    @Autowired
    private AdminInfoMapper adminInfoMapper;

    @Override
    public PageInfo<AdminInfo> selAdminInfoById(SelAdminInfoForm saif) {
        PageHelper.startPage(saif.getPageNum() != null ? saif.getPageNum() : 1, saif.getPageSize() != null ? saif.getPageSize() : 10);
        List<AdminInfo> adminInfoList = adminInfoMapper.selAdminInfoById(saif);
        System.out.println(adminInfoList);
        PageInfo<AdminInfo> pageInfo = new PageInfo<>(adminInfoList);
        return pageInfo;
    }

    @Override
    public AdminInfo login(LoginForm lf) {
        QueryWrapper<AdminInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("username",lf.getUsername());
        AdminInfo adminInfo = adminInfoMapper.selectOne(wrapper);
        System.out.println(adminInfo);
        // 判断用户是否存在
        if (adminInfo == null||adminInfo.getIsDelete().equals("0")) throw new ZsdException("用户名不存在", 20001);
        // 判断密码是否正确
        if (!adminInfo.getPassword().equals(lf.getPassword())) throw new ZsdException("密码错误", 20002);
        // 判断过期时间是否在当前系统日期之前
        if (adminInfo.getExpireTime() != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate expireDate = LocalDate.parse(adminInfo.getExpireTime(), formatter);
            if (expireDate.isBefore(LocalDate.now())) {
                throw new ZsdException("账户已过期", 20003);
            }
        }
        return adminInfo;
    }

    @Override
    public int insertAdminInfo(AdminInfoForm aif) {
        if(aif == null){
            return 0;
        }
        // 检查手机号是否已存在
        int phoneCount = adminInfoMapper.checkPhoneExists(aif.getPhone());
        if (phoneCount > 0) {
            throw new ZsdException("手机号已存在", 20004);
        }

        // 检查用户名是否已存在
        int usernameCount = adminInfoMapper.checkUsernameExists(aif.getUsername());
        if (usernameCount > 0) {
            throw new ZsdException("用户名已存在", 20005);
        }
        String expireTimeStr = null;  // 将expireTime存储为String类型
        if (aif.getExpireTime() != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(aif.getExpireTime(), formatter);
            expireTimeStr = localDate.format(formatter);  // 将Date转换为String
        }
        System.out.println(aif.getExpireTime());
        adminInfoMapper.insertAdminInfo(aif.getName(), aif.getPhone(), aif.getRole(), aif.getSiteId(), aif.getUsername(), expireTimeStr);  // 传入String类型的expireTime
        return 1;
    }

    @Override
    public int updateAdminInfo(UpdateAdminInfoForm uaif) {
        if(uaif == null){
            return 0;
        }
        // 使用 java.time 包进行日期转换
        String expireTimeStr = null;
        if (uaif.getExpireTime() != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(uaif.getExpireTime(), formatter);
            expireTimeStr = localDate.format(formatter);  // 将Date转换为String
        }
        adminInfoMapper.updateAdminInfo(uaif.getAdminId(), uaif.getName(), uaif.getPhone(), uaif.getRole(), uaif.getState(), uaif.getSiteId(), uaif.getUsername(), expireTimeStr);
        return 1;
    }

    @Override
    public int deleteAdminInfoById(Integer adminId) {
        if(adminId == null){
            return 0;
        }
        adminInfoMapper.deleteAdminInfoById(adminId);
        return 1;
    }


    // 实现批量查询的方法
    @Override
    public List<AdminInfo> selectAdminInfoByIds(Set<Integer> adminIds) {
        return adminInfoMapper.selectAdminInfoByIds(adminIds);
    }

    @Override
    public AdminInfoDto selAdminInfo(Integer adminId) {
        return adminInfoMapper.selectAdminInfo(adminId);
    }

    @Override
    public List<AdminInfo> selAll() {
        return adminInfoMapper.selectList(null);
    }

    @Override
    public void addNewUser(AddNewUserForm addNewUserForm, Integer adminId) {
        // 获取负责人的站点 ID
        AdminInfo adminInfo = adminInfoMapper.selectAdminInfoById(adminId);
        if (adminInfo == null) {
            throw new ZsdException("负责人不存在", 20006);
        }
        Integer siteId = adminInfo.getSiteId();

        // 检查手机号是否已存在
        int phoneCount = adminInfoMapper.checkPhoneExists(addNewUserForm.getPhone());
        if (phoneCount > 0) {
            throw new ZsdException("手机号已存在", 20004);
        }

        // 检查用户名是否已存在
        int usernameCount = adminInfoMapper.checkUsernameExists(addNewUserForm.getUsername());
        if (usernameCount > 0) {
            throw new ZsdException("用户名已存在", 20005);
        }

        String expireTimeStr = null;
        if (addNewUserForm.getExpireTime() != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(addNewUserForm.getExpireTime(), formatter);
            expireTimeStr = localDate.format(formatter);
        }

        // 设置临时工的站点 ID 和角色
        adminInfoMapper.insertAdminInfo(
                addNewUserForm.getName(),
                addNewUserForm.getPhone(),
                3, // 角色设置为 3
                siteId, // 站点 ID 设置为负责人的站点 ID
                addNewUserForm.getUsername(),
                expireTimeStr
        );
    }

    @Override
    public List<AdminInfo> getAdminsByAdminIdAndRole(Integer adminId) {
        // 1. 根据 adminId 查询 siteId
        Integer siteId = adminInfoMapper.selectSiteIdByAdminId(adminId);
        if (siteId == null) {
            throw new ZsdException("管理员不存在", 20007);
        }

        // 2. 根据 siteId 和 role 查询所有符合条件的 AdminInfo
        return adminInfoMapper.selectAdminsBySiteIdAndRole(siteId);
    }


    @Override
    public Integer getCustomerService() {
        List<AdminInfo> adminInfos = adminInfoMapper.selectList(new QueryWrapper<AdminInfo>().eq("role", 4));
        //从 adminInfos 随机一个角色为 4 的管理员
        int index = 0;
        if (adminInfos.size() > 0) {
            Random random = new Random();
            index = random.nextInt(adminInfos.size());
            return adminInfos.get(index).getAdminId();
        }
        return index;
    }
    @Override
    public boolean checkDuplicateInfo(Integer adminId, String username, String phone) {
        // 查询数据库中是否存在相同的账号或手机号，排除当前管理员
        QueryWrapper<AdminInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("admin_id", adminId) // 排除当前管理员
                .and(wrapper -> wrapper.eq("username", username).or().eq("phone", phone));
        return this.count(queryWrapper) > 0;
    }

    @Override
    public boolean updatePassword(Integer adminId, UpdatePasswordForm updatePasswordForm) {
        // 1. 根据 adminId 查询管理员信息
        AdminInfo adminInfo = adminInfoMapper.selectAdminInfoById(adminId);
        if (adminInfo == null) {
            throw new ZsdException("管理员不存在", 20006);
        }

        // 2. 校验旧密码是否正确
        if (!adminInfo.getPassword().equals(updatePasswordForm.getOldPassword())) {
            throw new ZsdException("旧密码错误", 20008);
        }

        // 3. 更新新密码
        adminInfo.setPassword(updatePasswordForm.getNewPassword());
        adminInfoMapper.updateById(adminInfo);

        return true;
    }
}